const wrapper = document.querySelector(".wrapper"),
musicImg = wrapper.querySelector(".img-area img"),
musicName = wrapper.querySelector(".song-details .name"),
musicArtist = wrapper.querySelector(".song-details .artist"),
playPauseBtn = wrapper.querySelector(".play-pause"),
prevBtn = wrapper.querySelector("#prev"),
nextBtn = wrapper.querySelector("#next"),
mainAudio = wrapper.querySelector("#main-audio"),
progressArea = wrapper.querySelector(".progress-area"),
progressBar = progressArea.querySelector(".progress-bar"),
musicList = wrapper.querySelector(".music-list"),
albumList = wrapper.querySelector(".album-list"),
moreMusicBtn = wrapper.querySelector("#more-music"),
moreAlbumBtn = wrapper.querySelector("#more-album"),  
closemoreMusic = musicList.querySelector("#close-music"),
closemoreAlbum = albumList.querySelector("#close-album");

// console.log(sermonArray.length);

 // Set the series being accessed
let series = 0; 
// Set the first audio of the series to be played    
let musicIndex = 1;  
// Pause the playing of the first audio
isMusicPaused = true;  

//Code the set the series and musicIndex variables 
//use the format https://JesusFocus.com?a=6&s=2  
const params = new URLSearchParams(window.location.search);
const noshowMsg = document.getElementById("showMsg");
const btnReceive = document.querySelector('#album-list-btn');
const showVideo1 = document.getElementById('video1');
const showVideo2 = document.getElementById('video2');
showVideo1.style.display = "none";
showVideo2.style.display = "none";

btnReceive.innerText = ''

let album = params.get('album'); 
let sermon = params.get ('sermon') ; 
// console.log("album = " + album + " and sermon = " + sermon);

// Check that albumInt and sermonInt are integers
let albumInt = album - 0;
let sermonInt = sermon - 0;

if(albumInt >=1 && albumInt <= 200){series = albumInt - 1};
if(sermonInt >=1 && sermonInt <= 100){musicIndex = sermonInt};
 console.log("series = " + series + " and musicIndex = " + musicIndex);

// create two separate ul tags, one for list and one for albums 
const ulTag = wrapper.querySelector("ul");
// console.log("ulTag = " + ulTag);
const ulTag2 = wrapper.querySelectorAll("ul")[1];

// Check which device is being used (/iPad|iPhone|iPod/.test(ua))
const getMobileOS = () => {
  const ua = navigator.userAgent
  if (/android/i.test(ua)) {
    return "Android"
  }
  else if (/iPhone|iPod/.test(ua)) {
    return "iOS"
  }
  return "Other"
}

const os = getMobileOS();
// alert(os);

// Load music as soon as the page is loaded 
window.addEventListener("load", ()=>{
  loadMusic(musicIndex);
  playingSong(); 
  playingAlbum();

    musicDuration = wrapper.querySelector(".max-duration");   // Getting the DOM of the class = max-duration span element
    musicDuration.innerText = `End`;                          // These works OK at load time

});
// --------------------------------------------------------------------
/*
// Just for Testing Purposes -----------------------------------
let fileNum = 0;
codeTestArea.innerText = "{File name: " + sermonArray[series][3][fileNum] + ", " + 
                  "artist: " + sermonArray[series][1] + ", " + 
                  "img: " + sermonArray[series][0] + ", " +        
                   "src: " + sermonArray[series][3][fileNum] + "} "
*/               
//----- Start of load music function --------------------
function loadMusic(indexNumb){
//  console.log("opening loadMusic");
  musicName.innerText = sermonArray[series][3][indexNumb - 1];
  musicArtist.innerText = sermonArray[series][1];
  musicImg.src = `images/${sermonArray[series][0]}.jpg`;   // The original had .src instead of .img
  mainAudio.src = `songs/${sermonArray[series][3][indexNumb - 1]}.mp3`;   // The original had .jpg instead of .mp3

// Wait until the audio is loaded into the audio element with id = main-audio, then get its duration
  mainAudio.addEventListener('loadedmetadata', function() {
    let mainAdDuration = mainAudio.duration;
    let totalMin = Math.floor(mainAdDuration / 60);
    let totalSec = Math.floor(mainAdDuration % 60);
    if(totalSec < 10){ //if sec is less than 10 then add 0 before it
      totalSec = `0${totalSec}`;
    }
    //The next line sets the max duration of the song *********************************************
    musicDuration.innerText = `${totalMin}:${totalSec}`;    // This works
  });
}
// ----- end of loadMusic function --------------------

function playMusic(){
//  console.log("opening playMusic");
  wrapper.classList.add("paused");
 var div = document.getElementById('play-pause');
  // The next line clears the previous play button
  div.innerHTML = '<i class="myIcon-pause-btn play"></i>';  

  mainAudio.play();

    // update song total duration 
    let mainAdDuration = mainAudio.duration;
    let totalMin = Math.floor(mainAdDuration / 60);
    let totalSec = Math.floor(mainAdDuration % 60);
    if(totalSec < 10){ //if sec is less than 10 then add 0 before it
      totalSec = `0${totalSec}`;
    }
    //The next line sets the max duration of the song 
    musicDuration.innerText = `${totalMin}:${totalSec}`;
  
}
//----- End of playMusic function --------------------

function pauseMusic(){
//  console.log("opening pauseMusic");
  wrapper.classList.remove("paused");
  // The next line clears the previous pause button
  var div = document.getElementById('play-pause');
  div.innerHTML = '<i class="myIcon-play-btn play"></i>';  

  mainAudio.pause();
}
//----- End of pauseMusic function --------------------

function prevMusic(){
//  console.log("opening prevMusic");
  musicIndex--; //decrement of musicIndex by 1
  //if musicIndex is less than 1 then musicIndex will be the array length so the last music play
  musicIndex < 1 ? musicIndex = sermonArray[series][3].length : musicIndex = musicIndex;
  loadMusic(musicIndex);
  playMusic();
  playingSong(); 
}
//----- End of prevMusic function --------------------

function nextMusic(){
//  console.log("opening nextMusic");
  musicIndex++; //increment of musicIndex by 1
  //if musicIndex is greater than array length then musicIndex will be 1 so the first music play
  musicIndex > sermonArray[series][3].length ? musicIndex = 1 : musicIndex = musicIndex;
  loadMusic(musicIndex);
  playMusic();
  playingSong();  
}
//----- End of nextMusic function --------------------

playPauseBtn.addEventListener("click", ()=>{
//  console.log("playPauseBtn.addEventListener click event has occurred");
  const isMusicPlay = wrapper.classList.contains("paused");
  //if isPlayMusic is true then call pauseMusic else call playMusic
  isMusicPlay ? pauseMusic() : playMusic();
  playingSong();
});
// --------------------------------------------------------------------
//prev music button event
prevBtn.addEventListener("click", ()=>{
//  console.log("prevBtn.addEventListener click event has occurred");
  prevMusic();
});
// --------------------------------------------------------------------
//next music button event
nextBtn.addEventListener("click", ()=>{
//  console.log("nextBtn.addEventListener click event has occurred");
  nextMusic();
});
// --------------------------------------------------------------------
// update progress bar width according to music current time
mainAudio.addEventListener("timeupdate", (e)=>{
  // console.log("mainAudio.addEventListener-time click event has occurred");
  const currentTime = e.target.currentTime; //getting playing song currentTime
  const duration = e.target.duration; //getting playing song total duration
  let progressWidth = (currentTime / duration) * 100;
  progressBar.style.width = `${progressWidth}%`;

  let musicCurrentTime = wrapper.querySelector(".current-time"),
  musicDuration = wrapper.querySelector(".max-duration");
  mainAudio.addEventListener("loadeddata", ()=>{
    // update song total duration
    let mainAdDuration = mainAudio.duration;
    let totalMin = Math.floor(mainAdDuration / 60);
    let totalSec = Math.floor(mainAdDuration % 60);
    if(totalSec < 10){ //if sec is less than 10 then add 0 before it
      totalSec = `0${totalSec}`;
    }
    //The next line sets the max duration of the song *********************************************
    musicDuration.innerText = `${totalMin}:${totalSec}`;
  });
  // update playing song current time
  let currentMin = Math.floor(currentTime / 60);
  let currentSec = Math.floor(currentTime % 60);
  if(currentSec < 10){ //if sec is less than 10 then add 0 before it
    currentSec = `0${currentSec}`;
  }
  musicCurrentTime.innerText = `${currentMin}:${currentSec}`;
});
// --------------------------------------------------------------------
// update playing song currentTime on according to the progress bar width
progressArea.addEventListener("click", (e)=>{
//  console.log("progressArea click event has occurred");
  let progressWidth = progressArea.clientWidth; //getting width of progress bar
  let clickedOffsetX = e.offsetX; //getting offset x value
  let songDuration = mainAudio.duration; //getting song total duration
  
  mainAudio.currentTime = (clickedOffsetX / progressWidth) * songDuration;
  playMusic(); //calling playMusic function
  playingSong();
});
// --------------------------------------------------------------------

//code for what to do when the song ends
mainAudio.addEventListener("ended", ()=>{
  setTimeout(()=>{
    nextMusic(); //calling nextMusic function
  },4000);
}); 

// --------------------------------------------------------------------
//show music list onclick of music icon
moreMusicBtn.addEventListener("click", ()=>{
//  console.log("moreMusicBtn event has occurred");
  musicList.classList.toggle("show");
});
// --------------------------------------------------------------------
closemoreMusic.addEventListener("click", ()=>{
//  console.log("closemoreMusic event has occurred");
noshowMsg.style.display = "none";
  moreMusicBtn.click();
});
// --------------------------------------------------------------------
//show album list onclick of music icon
moreAlbumBtn.addEventListener("click", ()=>{
//  console.log("moreAlbumBtn event has occurred");
  albumList.classList.toggle("show");
});
// --------------------------------------------------------------------
closemoreAlbum.addEventListener("click", ()=>{
//  console.log("closemoreAlbum event has occurred");
  moreAlbumBtn.click();
});

// --------------------------------------------------------------------

// Function to load the Li elements of the music-List DIV
function loadList(){
// hide the downloadHint
  noshowMsg.style.display = "none";

//  console.log("opening loadList");
  for (let i = 0; i < sermonArray[series][3].length; i++) {
    //let's pass the song name, artist from the array
  var spanNum ;

  // spanNum is used for the span id
  spanNum = "spanNum-" + (i + 1);

  let liTag = `<li li-index="${i + 1}">
  <div class="row">
  <span url-index="${i + 1}" id="sendurl" class="myIcon-send-url" ></span>
  <span url-index="${i + 1}" id="playthis" >${sermonArray[series][3][i]}</span>
  </div>
  <span id="${spanNum}" class="audio-duration" >9:99</span>
  <audio id="selectSong" class="${spanNum}" src="songs/${sermonArray[series][3][i]}.mp3"></audio>
  </li>`;
  // Could also use <span>${sermonArray[series][3][i]}<p>${sermonArray[series][1]}</span>

  // console.log("spanNum-" + i);
  // console.log("audioNum-" + i);

  //inserting the li inside ul tag
  ulTag.insertAdjacentHTML("beforeend", liTag); 

    let liAudioDurationTag = ulTag.querySelector(`#${spanNum}`);
    let liAudioTag = ulTag.querySelector(`.${spanNum}`);

  //  console.log("liAudioDurationTag = " + liAudioDurationTag);
  //  console.log("liAudioTag = " + liAudioTag); 

      liAudioTag.addEventListener("loadeddata", ()=>{
      let duration = liAudioTag.duration;
      let totalMin = Math.floor(duration / 60);
      let totalSec = Math.floor(duration % 60);
      if(totalSec < 10){ //if sec is less than 10 then add 0 before it
        totalSec = `0${totalSec}`;
      };

    //Setting the total duration of the audio
    liAudioDurationTag.innerText = `${totalMin}:${totalSec}`; 

    //Setting the t-duration attribute, with the total duration value  
    liAudioDurationTag.setAttribute("t-duration", `${totalMin}:${totalSec}`); 
    });
  }
}
loadList();

// --------------------------------------------------------------------
// Function to load the Li elements of the album-list DIV
function loadAlbum(){
//  console.log("opening loadAlbum");
  for (let i = 0; i < sermonArray.length; i++) {
    // Create an li row identifier for use with the span id and the audio class name
    albumNum = "albumNum-" + (i + 1);
    // Compose the Li record to be added to the ul
    let liTag = `<li >
    <div class="row">
      <span dn-index="${i + 1}" id="download" class="myIcon-download"></span>
      <span al-index="${i + 1}" class="download" id="${albumNum}" >${sermonArray[i][0]}</span>
    </div>
    </li>`;
    //inserting the li inside ul tag
    //NOTE: span id    = download is for the downloading of the album zip fileNum when the span is clicked
    //NOTE: span class = download is to identify the next album to be loaded when the span is clicked

    // Insert the liTag into each of the album li's
    ulTag2.insertAdjacentHTML("beforeend", liTag); 

  }
}
loadAlbum();

// console.log(sermonArray.length);
// console.log(sermonArray[series][0]);

// --------------------------------------------------------------------
function playingSong(){
//  console.log("opening playingSong");
  const allLiTag = ulTag.querySelectorAll("li");   // gets all of the li tags within ultag, which references the list ul
//  console.log("allLiTag[2] = " + allLiTag[2])
//  console.log("allLiTag.length = " + allLiTag.length)

  const clickedURL = wrapper.querySelectorAll("#sendurl"); 
//  console.log("clickedURL[2] = " + clickedURL[2])
//  console.log("clickedURL.length = " + clickedURL.length)

  const clickedSong = wrapper.querySelectorAll("#playthis"); 
//  console.log("clickedSong[2] = " + clickedSong[2])
//  console.log("clickedSong.length = " + clickedSong.length)

// console.log(allLiTag);
  
  for (let j = 0; j < allLiTag.length; j++) {
    let audioTag = allLiTag[j].querySelector(".audio-duration");
    
    if(allLiTag[j].classList.contains("playing")){
      allLiTag[j].classList.remove("playing");
      let adDuration = audioTag.getAttribute("t-duration");
      audioTag.innerText = adDuration;
    }

    //if the li tag index is equal to the musicIndex then add playing class in it
    if(allLiTag[j].getAttribute("li-index") == musicIndex){
      allLiTag[j].classList.add("playing");
      audioTag.innerText = "Playing";
    }

  // allLiTag[j].setAttribute("onclick", "clicked(this)");
    clickedURL[j].setAttribute("onclick", "clickedSendURL(this)");
    clickedSong[j].setAttribute("onclick", "clicked(this)");
 
  }
}

// --------------------------------------------------------------------
function playingAlbum(){
//  console.log("opening playingAlbum");
// First gets all of the li tags within ultag2, which references the album ul

// NOTE: The following are set in loadAlbum
// <span id="download" class="material-icons">download_for_offline</span>
// <span class="download" id="${albumNum}" >${sermonArray[i][0]}</span>

//  const allAlTag = ulTag2.querySelectorAll("li");   
  
  const clickedAlbumDownload = wrapper.querySelectorAll("#download");  
  const changetoAlbum = wrapper.querySelectorAll(".download");  

  // NOTE: 
//  console.log(clickedAlbumDownload[2]);
//  console.log(changetoAlbum[2]);
  
//  console.log(allAlTag);

  for (let j = 0; j < clickedAlbumDownload.length; j++) {
    clickedAlbumDownload[j].setAttribute("onclick", "clickedZipDownload(this)");
  }

  for (let j = 0; j < changetoAlbum.length; j++) {
    changetoAlbum[j].setAttribute("onclick", "clickedAlbum(this)");
//      console.log("changetoAlbum clicked with item = " + j)
  }

}
// --------------------------------------------------------------------++
//particular li clicked function
function clicked(element){
//  console.log("clicked event has occurred");
//  let getLiIndex = element.getAttribute("li-index");
let getURLIndex = element.getAttribute("url-index");

 console.log("The clicked function has been called and getURLIndex = " + getURLIndex);

  musicIndex = getURLIndex; //updating current song index with clicked li index
  loadMusic(musicIndex);
  playMusic();
  playingSong();
  moreMusicBtn.click();
}
// --------------------------------------------------------------------

//particular Album clicked function
function clickedAlbum(element){
  let getAlbumIndex = element.getAttribute("al-index");
  console.log("clickedAlbum event has occurred with getAlbumIndex = " + getAlbumIndex);
  series = getAlbumIndex - 1; 
  // Remove all of the List items from the music-list
  while (ulTag.hasChildNodes()) {
    ulTag.removeChild(ulTag.firstChild);
  }
  // console.log("clickedAlbum function called");
  loadList();
  pauseMusic();
  musicIndex = 1;   
  loadMusic(musicIndex);
  playMusic();
  playingSong(); 
  moreAlbumBtn.click();
}

const clickedAlbumDownload = document.querySelectorAll("#download");  
// From Album List - Download a particular Album
function clickedZipDownload(element){
  let getAlbumDownload = element.getAttribute("dn-index") - 1;
//  let btnReceive = document.querySelector('#album-list-btn');
  let btnDownload = document.querySelector('#album-list-btn-url');

  // console.log("clickedZipDownload event - getAlbumDownload = " + getAlbumDownload);
  btnDownload.href = "ZIPs/" + sermonArray[getAlbumDownload][0] + ".zip";
  // console.log("'$ZIPs/{sermonArray[getAlbumDownload][0]}.zip' = " + sermonArray[getAlbumDownload][0]);
  //  console.log("sermonArray[getAlbumDownload][0] = " + sermonArray[getAlbumDownload][0]);
  btnReceive.innerText = 'Download';
  setTimeout(()=>{
  btnReceive.innerText = ''
  },7000);
}

// From Music List - Obtain the audio tag for sending a url link
function clickedSendURL(element){
  let getAudioIndex = element.getAttribute("url-index");
  console.log("clickedSendURL event has occurred with getAudioIndex = " + getAudioIndex);

  var popupWin = document.getElementById("mypopup");
  navigator.clipboard.writeText("https://JesusFocus.com?album=" + `${series + 1}` + "&sermon=" + getAudioIndex);
  console.log("https://JesusFocus.com?album=" + `${series + 1}` + "&sermon=" + getAudioIndex);
  // popupWin.innerHTML = "URL copied to clipboard";

  noshowMsg.style.display = "inline";
  setTimeout(()=>{
    noshowMsg.style.display = "none";
  },3000);
}

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);
  
  var downloadHint = document.getElementById("mydownloadHint");
  downloadHint.innerHTML = "Copied: " + copyText.value;
}
  
function outFunc() {
  var downloadHint = document.getElementById("mydownloadHint");
  downloadHint.innerHTML = "Copied to clipboard";
}

function selectVideo(videoType){    
  var mySource;    
  switch(videoType){
    case 'Demo':
      mySource = "video/Tutorial-1.mp4";
      break;
    case 'Windows':
      mySource = "video/Windows.mp4";
      break;
    case 'iPhone':
      mySource = "video/iPhone.mp4";
      break;
    case 'Android':
      mySource = "video/Android.mp4";
      break;
    case 'Mac':
      mySource = "video/Mac.mp4";
      break;
  }
  var player = document.getElementById('video1');
  var mp4Vid = document.getElementById('demo');
 // player.pause();
  // Now simply set the 'src' property of the mp4Vid variable!!!!
  mp4Vid.src = mySource;
  showVideo1.style.display = "block";
  showVideo2.style.display = "block";

//  player.load();
//  player.play();
}

function videoStart(btnType) {
  showVideo1.style.display = "block";
  showVideo2.style.display = "block";
  var instructions = document.getElementById('demo');
  /*
  var source = document.createElement('source');
  source.setAttribute('src', 'video/windows.mp4');
  source.setAttribute('type', 'instructions/mp4');
  instructions.appendChild(source);
 */

  // scroll to top of screen 
  window.scrollTo(0, 0);

  instructions.play();

  switch(btnType){
    case "stop":
      instructions.pause();
      break;
    case "start":
      instructions.play();
      break;
      case "repeat":
        instructions.pause();
        video1.currentTime = 0;      
        instructions.load();      
        break;
      case "close":
        instructions.pause();
        video1.currentTime = 0;  
        showVideo1.style.display = "none";      
        showVideo2.style.display = "none";
      break;
  }
}